#!/usr/bin/python
# -*- coding: utf-8 -*-




import threading





from twisted.internet.protocol import Factory
from twisted.protocols.basic import LineReceiver
from twisted.internet import reactor

class Chat(LineReceiver):
    

    def __init__(self):
        self.received=[]


    def connectionMade(self):
        self.sendLine("who are u?")

    def connectionLost(self, reason):
        self.sendLine("bye!")


    def dataReceived(self, data):
        self.received.append(data)
        self.sendLine(data)
        print data

    def lineReceived(self, line):
        self.received.append(line)
        self.sendLine(line)
        print line




class ChatFactory(Factory):

    def __init__(self):
        pass

    def buildProtocol(self, addr):
        return Chat



class android_websocket:

    def __init__(self,port=7778,autostart=True):
        self.port=port
        self.autostart=autostart
        self.factory=ChatFactory()
        self.__startSocket__()
        if self.autostart:
            self.thread.start()
        
    def __socketInit__(self):
        reactor.listenTCP(self.port, self.factory)
        reactor.run(installSignalHandlers=0)
 
 

    def __startSocket__(self):
        self.thread=threading.Thread(target=self.__socketInit__, args=())









import struct

from twisted.internet.protocol import Protocol, ClientFactory
from twisted.protocols.basic import IntNStringReceiver


class SocketClientProtocol(IntNStringReceiver):
    """ The protocol is based on twisted.protocols.basic
        IntNStringReceiver, with little-endian 32-bit
        length prefix.
    """
    structFormat = "<L"
    prefixLength = struct.calcsize(structFormat)

    def stringReceived(self, s):
        self.factory.got_msg(s)

    def connectionMade(self):
        self.factory.clientReady(self)


class SocketClientFactory(ClientFactory):
    """ Created with callbacks for connection and receiving.
        send_msg can be used to send messages when connected.
    """
    protocol = SocketClientProtocol

    def __init__(
            self,
            connect_success_callback,
            connect_fail_callback,
            recv_callback):
        self.connect_success_callback = connect_success_callback
        self.connect_fail_callback = connect_fail_callback
        self.recv_callback = recv_callback
        self.client = None

    def clientConnectionFailed(self, connector, reason):
        self.connect_fail_callback(reason)

    def clientReady(self, client):
        self.client = client
        self.connect_success_callback()

    def got_msg(self, msg):
        self.recv_callback(msg)

    def send_msg(self, msg):
        if self.client:
            self.client.sendString(msg)



class sock_serv:
    
    
    def __init__(self):
        self.client = SocketClientFactory(
                        self.on_client_connect_success,
                        self.on_client_connect_fail,
                        self.on_client_receive)
        print "ttt"
        reactor.listenTCP("0.0.0.0", 7778, self.client)
        reactor.run()

    def on_client_connect_success(self):
        print 'Connected to server. Sending...'
        self.client.send_msg('hello')

    def on_client_connect_fail(self, reason):
        # reason is a twisted.python.failure.Failure  object
        print 'Connection failed: %s' % reason.getErrorMessage()

    def on_client_receive(self, msg):
        print 'Client reply: %s' % msg
        print 'Disconnecting...'
        #self.connection.disconnect()









